![]() |
![]() |
|
Convert the following loop to a tail-recursive version (both in Java1, and then in racket). Emphasize the similarities -- your functions should use the same-named variables to compute the same answer in the exact same way (e.g. initialize the variables the same way, and update them the same way). It's just that your code won't have a loop-construct like “for” or “while”. Be sure to include a purpose-statement for your helper-function; it should (of course) mention all of its parameters.
class TailRecursionPractice { /** @return 2^0 + 2^1 + 2^2 + ... + 2^(n-1). */ static long sumPowersOf2( int n ) { long sumSoFar = 0L; for (int i=0; i<n; i=i+1) { sumSoFar = sumSoFar + Math.pow(2,i); } return sumSoFar; // Btw: There is a much shorter implementation that you learned in discrete math. What is it? } } |
This page licensed CC-BY 4.0 Ian Barland Page last generated | Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |